﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FanPages.Server.Services.Contracts;
using FanPages.Server.Repostory.EFRepository.Model;
using FanPages.Common.DataAccess;
using FanPages.Common.Exceptions;
using FanPages.Server.Services.Transformers;

namespace FanPages.Server.Services
{
    public class ConfigurationService : IConfigurationService
    {
        IRepository<Configuration> repository = new EFRepository<Configuration>(new FanPagesEntities());

        public void Save(Contracts.Dto.ConfigurationDto configuration)
        {
            try
            {
                if (configuration.Id != 0)
                {
                    var entity = repository.First(x => x.Id == configuration.Id);
                    repository.Update(new ConfigurationTransformerSvc().ToExistingClient(configuration, entity));
                }
                else
                {
                    repository.Add(new ConfigurationTransformerSvc().ToClient(configuration));
                }
            }
            catch (Exception ex)
            {
                throw new ServiceException("ConfigurationService.Save exception", ex);
            }
        }

        public Contracts.Dto.ConfigurationDto GetById(int id)
        {
            try
            {
                return new ConfigurationTransformerSvc().ToDto(repository.First(x => x.Id == id));
            }
            catch (Exception ex)
            {
                throw new ServiceException("ConfigurationService.GetById exception", ex);
            }
        }

        public Contracts.Dto.ConfigurationDto GetByFanItem(Contracts.Dto.FanItemDto fanItem)
        {
            try
            {
                var config = repository.First(x => x.FanItem.Id == fanItem.Id);
                if (config != null)
                {
                    return new ConfigurationTransformerSvc().ToDto(config);
                }
                else
                    return null;
                
            }
            catch (Exception ex)
            {
                throw new ServiceException("ConfigurationService.GetByFanItem exception", ex);
            }
        }
    }
}
